package party.damao.issue.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import party.damao.issue.common.EnumMsgKey;
import party.damao.issue.common.EnumRestCode;
import party.damao.issue.common.RestObject;

@RestController
@RequestMapping("/api")
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @RequestMapping("/toLogin")
    public Object toLogin() {
        return RestObject.newInstance(EnumRestCode.notLogin.getValue(), EnumRestCode.notLogin.getDescription());
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Object login(@RequestBody JSONObject body) throws Exception {
        if (body == null || body.isEmpty()) {
            return RestObject.newInstance(EnumRestCode.errPwd.getValue(), EnumRestCode.errPwd.getDescription());
        }
        String account = body.getString("account");
        String password = body.getString("password");
        logger.info("==========" + account + password);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account, password);
        token.setRememberMe(true);
        try {
            subject.login(token);
            String accessToken = String.valueOf(subject.getSession().getId());
            System.out.printf("----token--->" + accessToken);
            return RestObject.newOK(EnumRestCode.ok.getDescription(), accessToken);
        } catch (AuthenticationException e) {
            logger.error(e.getMessage());
            return RestObject.newInstance(EnumRestCode.errPwd.getValue(), EnumRestCode.errPwd.getDescription());
        }
    }

    @RequestMapping(value = "/logout")
    public Object logout() throws Exception {
        try {
            SecurityUtils.getSubject().logout();
            return RestObject.newOK(EnumMsgKey.oper_success.getValue());
        } catch (Exception e) {
            logger.error(e.getMessage());
            return RestObject.newError(EnumMsgKey.oper_fail.getValue());
        }
    }
}
